//: concurrency/CallableDemo.java
package concurrency; /* Added by Eclipse.py */

import java.util.concurrent.*;
import java.util.*;

class TaskWithResult implements Callable<String> {
    private int id;

    public TaskWithResult(int id) {
        this.id = id;
    }

    public String call() {
        if (id == 1) {
            try {
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "result of TaskWithResult 111" + id;
        }
        if (id == 2) {
            try {
                TimeUnit.MILLISECONDS.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "result of TaskWithResult 111" + id;
        } else {
            return "result of TaskWithResult " + id;
        }

    }
}

public class CallableDemo {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(20);


        ArrayList<Future<String>> results =
                new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            results.add(exec.submit(new TaskWithResult(i)));
            System.out.println(i);
        }
        int i = 1;
        for (Future<String> fs : results)
            try {
                // get() blocks until completion:
//                System.out.println(fs.get());
                System.out.println(i++);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                exec.shutdown();
            }
    }
} /* Output:
result of TaskWithResult 0
result of TaskWithResult 1
result of TaskWithResult 2
result of TaskWithResult 3
result of TaskWithResult 4
result of TaskWithResult 5
result of TaskWithResult 6
result of TaskWithResult 7
result of TaskWithResult 8
result of TaskWithResult 9
*///:~
